const cheerio = require('cheerio');
const axios = require('axios')
const xlsx = require('node-xlsx');
const fs = require('fs')
export class buildExcelFactory {
  start() {
    axios.get('http://quotes.money.163.com/f10/zycwzb_600519.html#01c01').then(res => {
      // 获取htmlstr  解析出想要的数据
      let data = this.getExeclData(res.data)
      // 将数据利用xlsx生成excel
      this.createExcel(data)
    });
  }
  getExeclData(HTMLStr) {
    const $ = cheerio.load(HTMLStr);
    const $table = $('.table_bg001.scr_table');
    //获取表头 （年份dom列表）
    const $ths = $table.find('tbody tr').eq(0).children();
    // 获取表体 （想要的行数据dom列表）
    const $tds = $table.find('tbody tr').eq(12).children();
    const data = [[],[]]
    for (let i = 0; i < $ths.length; i++) {
      const TH = $($ths[i]).text().trim()
      const TD = $($tds[i]).text().trim().replace(/,/g, '')
      data[0].push(TH);
      data[1].push(TD);
    }
    return data
  }
  createExcel(data) {
    const buffers = xlsx.build([{ name: "茅台的净利润", data: data }]); // Returns a buffer
    fs.writeFileSync('茅台的净利润.xlsx', buffers, 'buffer');
    process.exit()
  }
}